package com.yzl.meeting.business.controller;

import com.yzl.meeting.business.entity.User;
import com.yzl.meeting.business.exception.BusinessException;
import com.yzl.meeting.business.rule.DataResult;
import com.yzl.meeting.business.rule.ResponseCode;
import com.yzl.meeting.business.service.Impl.UserServiceImpl;
import com.yzl.meeting.business.service.UserService;
import com.yzl.meeting.business.utils.CommonsUtils;
import com.yzl.meeting.business.utils.SendJMail;
import com.yzl.meeting.business.utils.VerifyCode;
import com.yzl.meeting.business.vo.UserInfVo;
import com.yzl.meeting.business.vo.UserVo;
import com.yzl.meeting.framework.annotation.Controller;
import com.yzl.meeting.framework.annotation.RequestBody;
import com.yzl.meeting.framework.annotation.RequestMapping;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;


@Controller("/user")
public class UserController {
    private UserService userService = new UserServiceImpl();

    @RequestMapping("/sendEmail")
    public DataResult sendEmail(HttpServletRequest req) throws Exception {
        String userName = CommonsUtils.getUserInf(req, "userName");
        String s = "1144946637@qq.com";
        String emailMsg="我是用户"+userName+",我需要协助";
        SendJMail.sendMail(s,emailMsg);
        return new DataResult<>(ResponseCode.SUCCESS);
    }
    @RequestMapping("/verify")
    public void verify(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        VerifyCode vc = new VerifyCode();
        BufferedImage image = vc.getImage();
        String text = vc.getText();
        req.getSession().setAttribute("code", text);
        VerifyCode.output(image, resp.getOutputStream());
    }

    @RequestMapping("/getUserInf")
    public User getUserInf(HttpServletRequest req) throws Exception {
        String userName = CommonsUtils.getUserInf(req,"userName");
        User userByUserName = userService.findUserByUserName(userName);
        String lastLoginTime = userByUserName.getLastLoginTime();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
        Date parse = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(lastLoginTime);
        long time1 = parse.getTime();
        Date date1 = new Date(time1);
        String format = sdf.format(date1);
        userByUserName.setLastLoginTime(format);
        return userByUserName;
    }

    @RequestMapping("/change")
    public DataResult changeUserInf(@RequestBody UserInfVo userInfVo, HttpServletRequest req){
        DataResult dataResult = null;
        try {
            System.out.println(userInfVo.toString());
            String userName = CommonsUtils.getUserInf(req,"userName");
            User user = userService.findUserByUserName(userName);
            BeanUtils.copyProperties(user,userInfVo);
            String date = userInfVo.getLastLoginTime();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
            long time = sdf.parse(date).getTime();
            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time);
            user.setLastLoginTime(format);

            userService.update(user);
            dataResult = new DataResult<>(ResponseCode.SUCCESS);
        }catch (SQLException e) {
            e.printStackTrace();
            dataResult = new DataResult((ResponseCode.SQLEXCEPTION));
        } catch (Exception e) {
            dataResult = new DataResult(ResponseCode.SYSTEMEXCEPTION);
        }
        return dataResult;
    }

    @RequestMapping("/logout")
    public DataResult logout(HttpServletRequest req) throws Exception {
        DataResult dataResult = null;
        Cookie[] cookies = req.getCookies();
        String userName = CommonsUtils.getUserInf(req,"userName");
        try {
            User userByUserName = userService.findUserByUserName(userName);
            userService.logout(userByUserName);
            dataResult = new DataResult<>(ResponseCode.SUCCESS);
            //cookie.setMaxAge(0);
        } catch (SQLException e) {
            dataResult = new DataResult((ResponseCode.SQLEXCEPTION));
        } catch (Exception e) {
            dataResult = new DataResult(ResponseCode.SYSTEMEXCEPTION);
        }

        return dataResult;
    }

    @RequestMapping("/verifyPwd")
    public DataResult verifyPwd(@RequestBody User user) throws Exception {
        DataResult dataResult = null;
        try {
            userService.verifyPassword(user);
            dataResult = new DataResult();
        }catch (Exception e){
            //异常有可能是 业务异常 ，还有可能是 SQL异常，或者其他异常
            if(e instanceof BusinessException){
                BusinessException be = (BusinessException)e;
                for(ResponseCode rc : ResponseCode.values()){
                    if(rc.getCode() == be.getCode()){
                        dataResult = new DataResult(rc);
                    }
                }
            }else if(e instanceof SQLException){
                dataResult = new DataResult(ResponseCode.SQLEXCEPTION);
            }else{
                dataResult = new DataResult(ResponseCode.SYSTEMEXCEPTION);
            }
        }
        return dataResult;
    }
    @RequestMapping("/updatePwd")
    public DataResult updatePwd(@RequestBody User user) throws Exception {
        String userName = user.getUserName();
        DataResult dataResult=null;
        try {
            User userByUserName = userService.findUserByUserName(userName);
            userByUserName.setPassword(user.getPassword());
            userService.update(userByUserName);
            dataResult=new DataResult();
        }catch (Exception e){
        if(e instanceof SQLException){
            dataResult = new DataResult(ResponseCode.SQLEXCEPTION);
        }else{
            dataResult = new DataResult(ResponseCode.SYSTEMEXCEPTION);

        }
    }
        return dataResult;
}




    @RequestMapping("/login")
    public DataResult<User> login(@RequestBody UserVo userVo, HttpServletRequest req) {
        DataResult<User> dataResult = null;

        String userName = userVo.getUserName();
        String password = userVo.getPassword();
        String inputCode = userVo.getCode();

        String code = (String) req.getSession().getAttribute("code");

        if (!inputCode.equalsIgnoreCase(code)) {
            dataResult = new DataResult<>(ResponseCode.VERIFYERROR);
            return dataResult;
        }
        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);
        try {
            User u = userService.login(user);
            dataResult = new DataResult<>(u);
        } catch (Exception e) {
            if (e instanceof BusinessException) {
                BusinessException be = (BusinessException) e;
                for (ResponseCode rc : ResponseCode.values()) {
                    if (rc.getCode() == be.getCode()) {
                        dataResult = new DataResult<>(rc);
                    }
                }
            } else if (e instanceof SQLException) {
                dataResult = new DataResult<>(ResponseCode.SQLEXCEPTION);
            } else {
                dataResult = new DataResult<>(ResponseCode.SYSTEMEXCEPTION);
            }
        }
        return dataResult;
    }
}

